/**
 * 语音合成工具
 */
export default class VoiceSynthesis {
  constructor(options = {}) {
    this.synthesis = window.speechSynthesis;
    this.voice = null;
    this.lang = options.lang || 'zh-CN';
    this.rate = options.rate || 1.0;
    this.pitch = options.pitch || 1.0;
    this.volume = options.volume || 1.0;
    this.onStart = options.onStart || (() => {});
    this.onEnd = options.onEnd || (() => {});
    this.onError = options.onError || (() => {});

    this.init();
  }

  init() {
    // 检查浏览器支持
    if (!('speechSynthesis' in window)) {
      console.error('您的浏览器不支持语音合成。');
      return;
    }

    // 加载语音
    this.loadVoices();
    
    // 有些浏览器可能需要等待voices加载
    if (speechSynthesis.onvoiceschanged !== undefined) {
      speechSynthesis.onvoiceschanged = this.loadVoices.bind(this);
    }
  }

  loadVoices() {
    // 获取可用的语音
    const voices = this.synthesis.getVoices();
    
    // 尝试找到中文语音
    this.voice = voices.find(voice => voice.lang.includes(this.lang)) || 
                voices.find(voice => voice.default) || 
                (voices.length ? voices[0] : null);
  }

  speak(text) {
    if (!this.synthesis) {
      console.error('语音合成不可用');
      return;
    }

    // 创建语音合成请求
    const utterance = new SpeechSynthesisUtterance(text);
    
    // 设置参数
    utterance.voice = this.voice;
    utterance.lang = this.lang;
    utterance.rate = this.rate;
    utterance.pitch = this.pitch;
    utterance.volume = this.volume;
    
    // 绑定事件
    utterance.onstart = this.onStart;
    utterance.onend = this.onEnd;
    utterance.onerror = this.onError;
    
    // 取消所有当前语音
    this.synthesis.cancel();
    
    // 开始语音合成
    this.synthesis.speak(utterance);
  }

  stop() {
    if (this.synthesis) {
      this.synthesis.cancel();
    }
  }

  pause() {
    if (this.synthesis) {
      this.synthesis.pause();
    }
  }

  resume() {
    if (this.synthesis) {
      this.synthesis.resume();
    }
  }

  setVoice(voiceName) {
    const voices = this.synthesis.getVoices();
    const voice = voices.find(v => v.name === voiceName);
    if (voice) {
      this.voice = voice;
      return true;
    }
    return false;
  }

  setRate(rate) {
    this.rate = Math.max(0.1, Math.min(10, rate));
  }

  setPitch(pitch) {
    this.pitch = Math.max(0, Math.min(2, pitch));
  }

  setVolume(volume) {
    this.volume = Math.max(0, Math.min(1, volume));
  }
}; 